package 线程池;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    //num: 员工数量
    public MyThreadPool(int num){
        for(int i=0; i<num; i++){
            //消费者：线程创建的时候，就创建消费者线程，不停的从队列取任务来执行
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {//不停的取任务
                        try {
                            Runnable task = queue.take();//阻塞的方式取
                            task.run();//执行任务
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

    public void execute(Runnable task){
        try {
            queue.put(task);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(5);
        while (true){
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
            Thread.sleep(1000);
        }
    }
}
